import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Switch,
  Row,
  Col,
  DatePicker,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SettingOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { userApi, roleApi } from '@/services/api';
import { useTableData } from '@/hooks/useTableData';
import SearchForm, { SearchField } from '@/components/SearchForm';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface User {
  id: number;
  username: string;
  email: string;
  nickname?: string;
  status: number;
  phone?: string;
  createTime: string;
  lastLoginAt?: string;
  userRoles?: UserRole[];
}

interface UserRole {
  id: number;
  roleId: number;
  role: Role;
}

interface Role {
  id: number;
  name: string;
  code: string;
  description?: string;
}

const Users: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [selectedRoles, setSelectedRoles] = useState<number[]>([]);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 使用通用的表格数据管理Hook
  const {
    data: users,
    loading,
    paginationConfig,
    refresh,
    search,
    reset,
  } = useTableData<User>({
    fetchData: userApi.getUsers,
    onError: (error) => message.error('获取用户列表失败'),
  });

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      render: (time?: string) => time ? new Date(time).toLocaleString() : '未登录',
    },
    {
      title: '角色',
      dataIndex: 'userRoles',
      key: 'userRoles',
      render: (userRoles?: UserRole[]) => (
        <div>
          {userRoles?.map(userRole => (
            <Tag key={userRole.id} color="blue">
              {userRole.role.name}
            </Tag>
          )) || '无角色'}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<SettingOutlined />}
            onClick={() => handleAssignRoles(record)}
          >
            角色配置
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];


  const fetchRoles = async () => {
    try {
      const response = await roleApi.getRoles();
      const roles = response.data?.list || response.list || response.data || response || [];
      setRoles(roles);
    } catch (error) {
      message.error('获取角色列表失败');
    }
  };

  const handleAdd = () => {
    setEditingUser(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setModalVisible(true);
    form.setFieldsValue(user);
  };

  const handleDelete = async (id: number) => {
    try {
      await userApi.deleteUser(id);
      message.success('删除成功');
      refresh();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingUser) {
        await userApi.updateUser(editingUser.id, values);
        message.success('更新成功');
      } else {
        await userApi.createUser(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      refresh();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleSearch = (values: any) => {
    search(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    reset();
  };

  const handleAssignRoles = async (user: User) => {
    setSelectedUser(user);
    setRoleModalVisible(true);
    
    // 设置用户当前的角色
    const currentRoleIds = user.userRoles?.map(ur => ur.roleId) || [];
    setSelectedRoles(currentRoleIds);
  };

  const handleSaveRoles = async () => {
    if (!selectedUser) return;

    try {
      // 确保角色ID是数字类型
      const roleIds = selectedRoles.map(id => Number(id));
      await userApi.assignRoles(selectedUser.id, roleIds);
      message.success('角色分配成功');
      setRoleModalVisible(false);
      refresh();
    } catch (error: any) {
      console.error('角色分配错误:', error);
      message.error(error.response?.data?.message || '角色分配失败');
    }
  };

  useEffect(() => {
    fetchRoles();
  }, []);

  const searchFields: SearchField[] = [
    { name: 'keyword', label: '关键词搜索', type: 'input', placeholder: '用户名/昵称/邮箱' },
    { name: 'username', label: '用户名', type: 'input', placeholder: '请输入用户名' },
    { name: 'email', label: '邮箱', type: 'input', placeholder: '请输入邮箱' },
    { name: 'phone', label: '手机号', type: 'input', placeholder: '请输入手机号' },
    {
      name: 'status',
      label: '状态',
      type: 'select',
      placeholder: '请选择状态',
      options: [
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' },
      ],
    },
    { name: 'createTimeRange', label: '创建时间', type: 'dateRange' },
    {
      name: 'sortBy',
      label: '排序字段',
      type: 'select',
      placeholder: '请选择排序字段',
      options: [
        { value: 'createTime', label: '创建时间' },
        { value: 'updateTime', label: '更新时间' },
        { value: 'lastLoginAt', label: '最后登录' },
      ],
    },
    {
      name: 'sortOrder',
      label: '排序方向',
      type: 'select',
      placeholder: '请选择排序方向',
      options: [
        { value: 'ASC', label: '升序' },
        { value: 'DESC', label: '降序' },
      ],
    },
  ];

  return (
    <div>
      {/* 查询表单 */}
      <SearchForm
        title="查询条件"
        fields={searchFields}
        onSearch={handleSearch}
        onReset={handleReset}
        form={searchForm}
        loading={loading}
      />

      {/* 主表单 */}
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增用户
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          scroll={{ y: 600 }}
          pagination={paginationConfig}
        />

        <Modal
          title={editingUser ? '编辑用户' : '新增用户'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => form.submit()}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, message: '用户名至少3个字符' },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' },
              ]}
            >
              <Input />
            </Form.Item>

            {!editingUser && (
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' },
                ]}
              >
                <Input.Password />
              </Form.Item>
            )}

            <Form.Item
              name="nickname"
              label="昵称"
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="phone"
              label="手机号"
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="status"
              label="状态"
              initialValue={1}
            >
              <Select>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title={`分配角色：${selectedUser?.username}`}
          open={roleModalVisible}
          onCancel={() => setRoleModalVisible(false)}
          onOk={handleSaveRoles}
          width={600}
        >
          <div style={{ marginBottom: 16 }}>
            <span>请选择要分配给用户的角色：</span>
          </div>
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择角色"
            value={selectedRoles}
            onChange={(values) => {
              // 确保选中的值都是数字类型
              const numericValues = values.map(v => Number(v));
              setSelectedRoles(numericValues);
            }}
          >
            {roles.map(role => (
              <Option key={role.id} value={role.id}>
                {role.name} ({role.code})
              </Option>
            ))}
          </Select>
          <div style={{ marginTop: 16, color: '#666' }}>
            <p>当前用户角色：</p>
            {selectedUser?.userRoles?.map(userRole => (
              <Tag key={userRole.id} color="blue" style={{ marginBottom: 4 }}>
                {userRole.role.name}
              </Tag>
            )) || <span>无角色</span>}
          </div>
        </Modal>
      </Card>
    </div>
  );
};

export default Users;